using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using System.Collections.ObjectModel;
using IngenEngine.Meshes;
using IngenEngine;
using System.Diagnostics;
using System.Windows.Forms;

namespace IngenEngine
{
	public class SceneManager
	{
		Collection<ICustomMeshable> objects;
		Engine engine;
		Device device;
		Stopwatch stopwatch;
		Form mainForm;
		bool running;

		public bool Running
		{
			get { return running; }
			set { running = value; }
		}

		public SceneManager(Form mainForm)
		{
			this.mainForm = mainForm;
			objects = new Collection<ICustomMeshable>();
			stopwatch = new Stopwatch();
			running = true;
		}

		/// <summary>
		/// Initializes the Ingen engine
		/// </summary>
		public void Init()
		{
			engine = new Engine(mainForm);
			this.device = engine.Device;
		}
		/// <summary>
		/// Loads and configures all objects, lights, etc. needed for the scene
		/// </summary>
		public void Load()
		{
			// Get some objects 
			Island newIsland = new Island(engine.Device);
			newIsland.X = 0.0f;
			newIsland.Y = 0.0f;
			newIsland.Z = 0.0f;
			newIsland.Yaw = 1.0f;
			newIsland.Pitch = 0.0f;
			newIsland.Roll = 0.0f;
			objects.Add(newIsland);
		}

		/// <summary>
		/// The engine loop
		/// </summary>
		public void Start()
		{
			//Game Loop
			while (running)
			{
				stopwatch.Reset();
				stopwatch.Start();
				Application.DoEvents();

				// render here
				if (running)
					engine.Run(
						delegate
						{
							// game physics

							// game mechanics

							int count = this.objects.Count;
							for (int x = 0; x < count; ++x)
								MeshHelper.DrawMeshHelper(ref this.device,
									this.objects[x].MeshInfo, this.objects[x].Yaw,
									this.objects[x].Pitch, this.objects[x].Roll,
									this.objects[x].X, this.objects[x].Y,
									this.objects[x].Z);
						});

				//Restrict framerate to ~60fps
				while ((double)stopwatch.ElapsedMilliseconds < 16.67) ;
				stopwatch.Stop();
			}
		}
	}
}